//! 已停止
const puppeteer = require("puppeteer");
const moment = require("moment");

const { createMobile, config } = require("../../../common/mobile");
const { info, saveFile, logging, reporter } = require("../../../common/util");

const name = "vd";
const today = moment().format("YYYY-MM-DD");
const logdir = `./logs/${today}/de/vd/${info.deviceid}`;

const r = reporter(name);
const logger = logging(name, logdir);

(async () => {
  const browser = await puppeteer.launch(config);
  const page = await browser.newPage();

  const m = await createMobile(page);

  //sub status linstener
  m._page.on("response", response => {
    let url = response.url();
    let status = response.status();

    if (url.startsWith("http")) {
      logger.info(`${response.request().method()}`, status, url);
    }

    if (url.startsWith("https://services.dimoco.at/dcb/AT/mobilkom/redir")) {
      r.s("success");
    }

    if (url.startsWith("http://google.com")) {
      r.w("failure", url);
      m.close();
    }
  });

  //开始
  try {
    r.i("start");

    logger.info("start");

    await m.get(`http://offer.lpaosub.com/offer/track?of=1015`);

    // await m._page.waitForNavigation({ timeout: 300000 });
    //等待页面加载完成
    await m._page.waitForSelector("button[class='btn btn-warning btn-lg']");

    //保存页面
    saveFile(`${logdir}/1.html`, await m._page.content());
    logger.info("save1");

    // 进入订阅页面
    await m.evaluate(() => {
      document.getElementsByClassName("btn btn-warning btn-lg")[0].click();
    });

    await m._page.waitForNavigation({ timeout: 300000 });

    await m._page.waitForSelector("span[class='checkmark']");
    await m._page.waitForSelector("#continueButton");

    saveFile(`${logdir}/2.html`, await m._page.content());
    logger.info("save2");

    await m.sleep(1000);
    // 点击订阅按钮
    await m.evaluate(() => {
      document.getElementsByClassName("checkmark")[0].click();
    });
    await m.tapElement("#continueButton");

    logger.info("check1");

    await m._page.waitForNavigation({ timeout: 300000 });

    await m._page.waitForSelector("#sbtPin");

    saveFile(`${logdir}/3.html`, await m._page.content());
    logger.info("save3");

    await m.sleep(1000);

    await m.tapElement("#sbtPin");

    logger.info("submit");

    await m.waitForNavigation();

    logger.info("end");

    r.i("end");
  } catch (e) {
    saveFile(`${logdir}/error.html`, await m._page.content());
    r.e(e + "");
    logger.error(e);
  } finally {
    await m.close();
  }
  await browser.close();
})();
